<script setup lang="ts">
import { showToast, type ActionSheetAction } from 'vant'
import { onMounted, ref } from 'vue'
import { flattenAreaData, type Area } from '@/utils/area'
import b64ToBlob from 'b64-to-blob'
import { request } from '@/api'

interface IPickerParams {
  selectedValues: string[]
  selectedOptions: {
    text: string
    value: string
  }[]
  selectedIndexes: number[]
}

// 1. 修改头像
// 1.1 控制修改头像弹层的显示/隐藏
const showAvatarSheet = ref(false)
// 1.2 打开相册/相机
const onSelectAvatar = async (item: ActionSheetAction, i: number) => {
  showAvatarSheet.value = false
  if (i === 0) {
    // 相册上传
    // 1. 下包 pnpm i
    // 2. 拿到base64
    const b64Str = await HDM.pickerPhoto()

    // 3. 转换为2进制blob
    const file = b64ToBlob(b64Str, 'image/jpeg')

    // 4. fd组装数据
    const fd = new FormData()
    fd.append('file', file, Date.now() + '.jpeg')


    // 5 .
    const res = await request.post('member/profile/avatar', fd)

    profile.value.avatar = res.data.result.avatar

    showToast('上传成功')
  } else if (i === 1) {
    // 拍照上传
    console.log('拍照上传');
  }

}

// 控制日期选择器, 选择生日
const isShowBirth = ref(false)
const onSelectBirth = ({ selectedValues }: IPickerParams) => {
  profile.value.birthday = selectedValues.join('-')
  isShowBirth.value = false
}
// 地区选择器
const isShowArea = ref(false)

// 5.2
const columns = ref<Area[]>([])

// 4. 获取鸿蒙端传来的省市区数据
const str = HDM.getAreaColumns()
// 5.1 存到Column上去
columns.value = JSON.parse(str)
// 6 配置字段名
const areaData = flattenAreaData(JSON.parse(str))
const onSelectArea = (data: IPickerParams) => {
  const pName = areaData[data.selectedValues[0]]
  const cName = areaData[data.selectedValues[1]]
  const aName = areaData[data.selectedValues[2]]

  // 1. 收集省市区的code
  profile.value.provinceCode = data.selectedValues[0]
  profile.value.cityCode = data.selectedValues[1]
  profile.value.countyCode = data.selectedValues[2]

  profile.value.fullLocation = `${pName} ${cName} ${aName}`
  isShowArea.value = false
}
// :columns-field-names="{ text: 'name', value: 'code', children: 'areaList' }"


// 4. 选择职业
const columnsPro = [
  { text: '软件工程师', value: '软件工程师' },
  { text: '医生', value: '医生' },
  { text: '教师', value: '教师' },
  { text: '律师', value: '律师' },
  { text: '会计师', value: '会计师' },
  { text: '销售经理', value: '销售经理' },
  { text: '市场营销专员', value: '市场营销专员' },
  { text: '建筑师', value: '建筑师' },
  { text: '护士', value: '护士' },
  { text: '机械工程师', value: '机械工程师' }
]
const showProfessionPopup = ref(false)
const onChangeProfession = (data: { selectedValues: string[] }) => {
  showProfessionPopup.value = false
  profile.value.profession = data.selectedValues[0]
}


// 1. 查数据和存数据
const profile = ref({} as HDMUser)
onMounted(() => {
  profile.value = HDM.getUser()
})

// 2. 绑定点击事件
const onSubmit = async () => {
  // 3. 调用保存的接口
  const res = await request.put('/member/profile', profile.value)
  console.log('res  ----->  ', res)
  // 4. 更新数据到鸿蒙App
  // 5. 修复用户数据更新到首选项中
  if (res.status === 200) {
    HDM.setUser(profile.value)
    showToast('保存成功')
    setTimeout(() => HDM.backApp(), 300)
  } else {
    showToast('上传失败')
  }
}
</script>

<template>
  <div class="profile-edit-page">
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image round width="100" height="100" class="avatar-img" :src="profile.avatar">
        @click="showAvatarSheet = true">
      </van-image>
      <div class="avatar-btn">
        <span @click="showAvatarSheet = true">修改头像</span>
      </div>
    </div>
    <!-- 中间表单部分 -->
    <van-cell-group>
      <van-field label="账号" readonly v-model="profile.account"></van-field>
      <van-field label="昵称" placeholder="请输入昵称" v-model="profile.nickname"></van-field>
      <van-cell title="性别" class="gender">
        <van-radio-group :icon-size="16" v-model="profile.gender">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>
      <van-field label="生日" readonly placeholder="请选择日期" @click="isShowBirth = true" v-model="profile.birthday" />
      <van-field label="所在地" readonly placeholder="请选择所在地" @click="isShowArea = true" v-model="profile.fullLocation" />
      <van-field label="职业" readonly placeholder="请选择职业" @click="showProfessionPopup = true"
        v-model="profile.profession" />
    </van-cell-group>

    <div class="submit">
      <van-button round block type="primary" @click="onSubmit"> 保存资料 </van-button>
    </div>
    <van-action-sheet v-model:show="showAvatarSheet" :actions="[{ name: '相册' }, { name: '拍照' }]"
      @select="onSelectAvatar" cancel-text="取消" :style="{ paddingBottom: '20px' }"></van-action-sheet>

    <VanPopup title="选择生日" v-model:show="isShowBirth" position="bottom">
      <VanDatePicker :model-value="profile.birthday.split('-')" @cancel="isShowBirth = false" @confirm="onSelectBirth"
        :min-date="new Date('1950-01-01')" :max-date="new Date('2050-12-31')" />
    </VanPopup>

    <VanPopup title="选择地区" v-model:show="isShowArea" position="bottom">
      <VanPicker @confirm="onSelectArea" :columns-field-names="{ text: 'name', value: 'code', children: 'areaList' }"
        :columns="columns">
      </VanPicker>
    </VanPopup>


    <van-popup title="选择职业" v-model:show="showProfessionPopup" round position="bottom">
      <van-picker :columns="columnsPro" @confirm="onChangeProfession" @cancel="showProfessionPopup = false" />
    </van-popup>
  </div>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>
